//
//  AppDelegate.swift
//  microblog
//
//  Created by 安波 on 15/10/26.
//  Copyright © 2015年 anbo. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    

    var window: UIWindow?

    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        UIApplication.sharedApplication().applicationIconBadgeNumber = 6
        
//        print(isNewVersion()) // 注意：在最终代码执行的时候，不能随意调用“打印方法”，否则，会出现莫名的错误
        
        //打印归档的数据
//        print("启动 account:\(ABUserAccount.loadAccount())")
        
        // 设置全局外观
        setupAppearence()
        
        // 创建窗口
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        // 添加窗口跟控制
        let tabBar = ABMainTabBarController()
//        window?.rootViewController = tabBar
        tabBar.view.backgroundColor = UIColor.redColor()
        window?.rootViewController = defaultController()
        
        //设置窗口为主窗口 并显示
        window?.makeKeyAndVisible()
        return true
    }
    
    // 判断显示窗口
    private func defaultController() -> UIViewController {
        // 判断是否登录
        // 每次登录都需要 == nil
        if !ABUserAccount.userLogin(){
            return ABMainTabBarController()
        }
        
        return isNewVersion() ? ABNewFeatureController() : ABWelcomeController()
    }
    
    /// 判断是否有新版本
    private func isNewVersion() -> Bool {
        // 获取当前班版本号
        let versionString = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let currentVersion = Double(versionString)!
//        print("currentVersion : \(currentVersion)")
        
        // 获取之前版本号
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
//        print("sandboxVersion : \(sandboxVersion)")
        
        // 保存当前版本号
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
        NSUserDefaults.standardUserDefaults().synchronize()
        
        // 对比
        return currentVersion > sandboxVersion
        
    }
    
    /// 设置全局外观
    private func setupAppearence(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
    // MARK: - 切换根控制器
    /**
    切换根控制器
    - parameter isMain: true: 表示切换到MainViewController, false: welcome
    */
    func switchRootController(isMain: Bool){
        window?.rootViewController = isMain ? ABMainTabBarController() : ABWelcomeController()
    }

}

